#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>


//用户端一般会内置服务端的ip和port，所以我们需要传入服务端ip和port两项
void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " serverip serverport" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        std::cout << "create socket errror" << std::endl;
        return 0;
    }
    //客户端不需要显示绑定ip和port，OS会自动为其绑定，因为如果你使用了端口8080，但是另一个进程的客户端也使用了8080，不就乱了吗
    //所以OS随机分配是为了保证端口号不会冲突
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());//将string改为uint32_t并主机转网络
    server.sin_port = htons(serverport);

    while(true)
    {
        std::cout << "Please Enter@ ";
        std::string line;
        getline(std::cin, line);
        socklen_t serverlen = sizeof(server);
        sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr*)&server, serverlen);

        struct sockaddr_in temp;
        memset(&temp, 0, sizeof(temp));
        char buffer[1024];
        socklen_t templen = sizeof(temp);
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&temp, &templen);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }
    return 0;
}
